package walletuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/uniqueid"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserApplyWithdrawLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserApplyWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserApplyWithdrawLogic {
	return &UserApplyWithdrawLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户申请提现
func (l *UserApplyWithdrawLogic) UserApplyWithdraw(in *pb.UserApplyWithdrawReq) (*pb.UserApplyWithdrawResp, error) {
	defer utils.RecoverPanic()

	// 查询用户钱包
	var uw *wallet.UserWallet
	var err error
	uw, err = l.svcCtx.UserWalletModel.FindOneByUidMoneyType(l.ctx, in.Uid, in.MoneyType)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		if err == wallet.ErrNotFound {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletNotFound, "wallet not found")
		}
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	// 判断余额是否足够
	var dOutMoneyAmount decimal.Decimal
	dOutMoneyAmount, err = decimal.NewFromString(in.MoneyAmount)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}
	dOutMoneyAmount = dOutMoneyAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale))
	var dUWMoneyAmount = decimal.NewFromInt(uw.Amount)

	l.Logger.Infof("in.MoneyAmount %d uw.Amount %d ", dOutMoneyAmount.IntPart(), uw.Amount)
	if dUWMoneyAmount.LessThan(dOutMoneyAmount) {
		l.Logger.Errorf("err == ", zap.Error(xerr.NewGrpcErrCodeMsg(xerr.WalletBalanceNotEnoughForWithdraw, "amount not enough")))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.WalletBalanceNotEnoughForWithdraw, "amount not enough")
	}

	var dCurrencyAmount decimal.Decimal
	// 查询兑换比例
	var cfg *wallet.CurrencyExchangeConfig

	var dServiceFeeAmount decimal.Decimal
	var dServiceFeeRate decimal.Decimal
	if in.IsInput == dbkey.Enable { // 任意金额
		// 查询币种配置
		var wmc *wallet.WalletMoneyConfig
		wmc, err = l.svcCtx.WalletMoneyConfigModel.FindOne(l.ctx, in.MoneyType)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}

		// 判断提现金额是否超过最小最大限制
		dMax := decimal.NewFromInt(wmc.MaxWithdrawAmount)
		dMin := decimal.NewFromInt(wmc.MinWithdrawAmount)
		if dOutMoneyAmount.GreaterThan(dMax) || dOutMoneyAmount.LessThan(dMin) {
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "amount not allow withdraw")
		}

		cfg, err = l.svcCtx.CurrencyExchangeConfigModel.FindConfig(l.ctx, in.MoneyType, 0, in.CurrencyType, 1, in.PayChannelId)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			if err == wallet.ErrNotFound {
				return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "not find config")
			}
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}

		// 计算兑换金额
		var dCfgMoneyAmount = decimal.NewFromInt(cfg.MoneyAmount).Mul(decimal.NewFromInt(walletkey.MoneyScale))
		dCurrencyAmount = dOutMoneyAmount.Div(dCfgMoneyAmount).RoundFloor(2)
		// 计算手续费
		dServiceFeeRate = decimal.NewFromInt(cfg.ServiceFeeRate)
		dServiceFeeAmount = dCurrencyAmount.Mul(dServiceFeeRate).Div(decimal.NewFromInt(walletkey.MoneyScale)).Round(2)
	} else { // 固定金额
		cfg, err = l.svcCtx.CurrencyExchangeConfigModel.FindConfig(l.ctx, in.MoneyType, dOutMoneyAmount.IntPart(), in.CurrencyType, 0, in.PayChannelId)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
		dCurrencyAmount = decimal.NewFromInt(cfg.CurrencyAmount).Mul(decimal.NewFromInt(walletkey.MoneyScale))
		dServiceFeeRate = decimal.NewFromInt(cfg.ServiceFeeRate)
		dServiceFeeAmount = dCurrencyAmount.Mul(dServiceFeeRate).Div(decimal.NewFromInt(walletkey.MoneyScale)).Round(2)
	}

	// 计算提现金额
	iOutMoneyAmount := dOutMoneyAmount.RoundFloor(2).IntPart()
	dCurrencyAmount = dCurrencyAmount.Sub(dServiceFeeAmount)
	iCurrencyAmount := dCurrencyAmount.Mul(decimal.NewFromInt(walletkey.MoneyScale)).IntPart()

	var uwf = wallet.UserWithdrawFlow{
		FlowNo:           uniqueid.GenFlowNoX(),
		Uid:              uw.Uid,
		MoneyType:        uw.MoneyType,
		MoneyAmount:      iOutMoneyAmount,
		CurrencyType:     in.CurrencyType,
		CurrencyAmount:   iCurrencyAmount,
		PayChannelId:     in.PayChannelId,
		AccountName:      in.AccountName,
		BankCardNumber:   in.BankCardNumber,
		BankName:         in.BankName,
		BankCode:         in.BankCode,
		AccountType:      in.AccountType,
		ServiceFeeRate:   0,
		ServiceFeeAmount: 0,
		AuditAdminUid:    0,
		AuditMsg:         "",
		State:            walletkey.WithdrawFlowStateNotAudit,
	}
	l.Logger.Infof("apply withdraw ", zap.Int64("MoneyType", uwf.MoneyType), zap.Int64("MoneyAmount", uwf.MoneyAmount),
		zap.Int64("CurrencyType", uwf.CurrencyType), zap.Int64("CurrencyAmount", uwf.CurrencyAmount))

	uwf.ServiceFeeAmount = dServiceFeeAmount.IntPart()
	uwf.ServiceFeeRate = dServiceFeeRate.IntPart()

	err = l.svcCtx.UserWalletModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		// 更新钱包余额
		err2 := l.svcCtx.UserWalletModel.DecrAmountTrans(ctx, tx, iOutMoneyAmount, uw.Id, uw.Uid, uw.MoneyType)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		// 创建提现流水
		_, err2 = l.svcCtx.UserWithdrawFlowModel.InsertTrans(ctx, tx, &uwf)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	var rsp pb.UserApplyWithdrawResp
	rsp.CurrencyAmount = dCurrencyAmount.String()
	rsp.CurrencyType = in.CurrencyType
	rsp.FlowNo = uwf.FlowNo
	rsp.MoneyType = uw.MoneyType
	rsp.Balance = dUWMoneyAmount.Sub(dOutMoneyAmount).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)
	rsp.ServiceFeeRate = dServiceFeeRate.Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)
	rsp.ServiceFeeAmount = dServiceFeeAmount.Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)

	// 发送通知
	//l.after(uw.Uid, walletkey.GetMoneyNameByMoneyType(in.MoneyType), in.MoneyAmount)
	return &rsp, nil
}

//func (l *UserApplyWithdrawLogic) after(uid int64, moneyName, moneyAmount string) {
//	kqMsg := kqmsg.KqAddUserNotifyMsg{
//		Uid:     uid,
//		Title:   userkey.UserNotifyMsgTitleWithdrawCreated03EnIn,
//		MsgType: userkey.UserNotifyMsgTypeWithdrawCreated03,
//	}
//
//	msgContent := userkey.UserNotifyMsgContent1{
//		Text:     fmt.Sprintf(userkey.UserNotifyMsgContentWithdrawCreated03EnIn, moneyAmount, moneyName),
//		Url:      "",
//		PagePath: "",
//	}
//	var cBuf []byte
//	cBuf, err := json.Marshal(msgContent)
//	if err != nil {
//		l.Logger.Errorf("UserApplyWithdrawLogic after json.Marshal(msgContent) err:%v", err)
//		return
//	}
//	kqMsg.MsgContent = string(cBuf)
//
//	var kqMsgBuf []byte
//	kqMsgBuf, err = json.Marshal(kqMsg)
//	if err != nil {
//		l.Logger.Errorf("UserApplyWithdrawLogic after json.Marshal(kqMsg) err:%v", err)
//		return
//	}
//
//	err = l.svcCtx.KqAddUserNotifyMsgClient.Push(string(kqMsgBuf))
//	if err != nil {
//		l.Logger.Errorf("UserApplyWithdrawLogic after Push err:%v", err)
//		return
//	}
//	return
//}
